const resourcesProxy = require('../proxy/resources')
const fs = require('fs')
// const ossClient = require('../common/aliyun-oss')
const path = require('path')

exports.putResources = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'resources')) {
    return res.status(403).end()
  }
  try {
    if (req.files.length > 0) {
      // save info into db
      req.files.splice(5)
      const { teamId, userId } = req.user
      const data = []
      for (const file of req.files) {
        data.unshift(await resourcesProxy.saveFileInTeamBySb(file, teamId, userId))
      }
      // upload to oss
      res.json({ saved: data })
    } else {
      res.sendStatus(204)
    }
  } catch (err) {
    console.log(err)
    next(err)
  }
}

exports.getResourcesList = async function(req, res, next) {
  const { teamId } = req.params
  if (teamId !== req.user.teamId) {
    return res.status(403).end()
  }
  try {
    let { page, per_page } = req.query
    if (!page || page < 1) page = 1
    if (!per_page || per_page < 1) per_page = 50
    const items = await resourcesProxy.getAllResourcesInTeam(teamId, (page - 1) * per_page, per_page * 1)
    res.json({ items })
  } catch (err) {
    next(err)
  }
}

exports.downloadResource = async function(req, res, next) {
  const { teamId } = req.user
  const { id } = req.params
  try {
    const resource = await resourcesProxy.existResourceInTeam(id, teamId)
    if (!resource) throw new Error('not found')
    else {
      res.download(path.join(__dirname, '../uploads', resource.savedFileName))
    }
  } catch (err) {
    next(err)
  }
}

exports.deleteResource = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'resources')) {
    return res.status(403).end()
  }
  try {
    const resource = await resourcesProxy.deleteResourceInTeam(req.params.id, req.user.teamId)
    res.sendStatus(204)
    fs.unlink(path.join(__dirname, '../uploads', resource.savedFileName))
  } catch (err) {
    next(err)
  }
}
